﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Talentnet.Core.Utilities
{
    public class TextResourceLoader
    {
        const string TEXT_RES_TPL = "texRes-{0}.xml";
        string _rootFolder = "", _resFile, _langKey;
        public TextResourceLoader(string rootFolder, string languageKey)
        {
            _langKey = languageKey;
            _rootFolder = rootFolder;
            _rootFolder = _rootFolder.Replace("/", "\\");
            if (!_rootFolder.EndsWith("\\")) _rootFolder += "\\";
            _resFile = _rootFolder + TEXT_RES_TPL.Replace("{0}", languageKey);
        }
        public void SwitchLanguage(string languageKey)
        {
            _langKey = languageKey;
            _resFile = _rootFolder + TEXT_RES_TPL.Replace("{0}", languageKey);
        }
        string _sessionID = "";
        public void SetSession(string sessionID)
        {
            _sessionID = sessionID;
        }
        public string GetText(string key)
        {
            return GetText(_sessionID, key);
        }
        public string GetText(string sessionID, string key)
        {
            XmlDocument resDoc = null;
            if (System.Web.HttpRuntime.Cache["TextResource" + _langKey] == null)
            {
                resDoc = new System.Xml.XmlDocument();
                resDoc.Load(_resFile);
                System.Web.HttpRuntime.Cache.Insert("TextResource" + _langKey, resDoc, new System.Web.Caching.CacheDependency(_resFile));
            }
            else
            {
                resDoc = (XmlDocument)System.Web.HttpRuntime.Cache["TextResource" + _langKey];
            }
            XmlNodeList textNodes = resDoc.SelectNodes("//res/sessions/session[@id='" + sessionID + "']/text[@key='" + key + "']");
            if (textNodes == null) return "[Text Not Found: " + sessionID + " - " + key + "]";
            if (textNodes.Count == 0) return "[Text Not Found: " + sessionID + " - " + key + "]";
            return textNodes[0].Attributes["value"].Value;
        }
    }

}
